import request from '../../utils/request';
Component({
  behaviors: [require('../common/share-behavior').default],//共享组应用
  properties: {
    a: Number,
    modelUrl: {
      type: String,
      value: 'https://xrmini.dwtcy.com.cn/Terrain.glb'
    },
  },
  data: {
    loaded: false,
    arReady: false,
    modelList: [],
  },
  observers: {
    'modelUrl': function(modelUrl) {
      // console.log('modelUrl changed:', modelUrl);
      // 当modelUrl变化时清理旧资源
      if (this.scene) {
        this.clearOldModel();
      }
    }
  },
  lifetimes: {
    async attached() {
      // console.log('data', this.data)
      
      // 调用getModel接口获取模型数据
      
      // 注释掉获取位置，使用默认经纬度（常州市）
      // wx.getLocation({
      //   type: 'wgs84',
      //   success: (res) => {
      //     this.data.originLat = res.latitude;
      //     this.data.originLon = res.longitude;
      //     // console.log('AR 场景起始位置:', this.data.originLat, this.data.originLon);
      //   },
      //   fail: () => {
      //     // console.warn('无法获取初始位置，请授权定位权限');
      //   }
      // });
      
      // 设置默认经纬度（常州市）
      this.data.originLat = 31.78; // 常州市纬度
      this.data.originLon = 119.95; // 常州市经度
    }
  },
  methods:{
    handleReady({ detail }){
      const xrScene = this.scene = detail.value;
      this.mat = new (wx.getXrFrameSystem().Matrix4)();
      // console.log('xr-scene', xrScene);
      this.xrFrameSystem = wx.getXrFrameSystem();
      // 删除旋转和缩放的触摸事件监听
      // this.scene.event.add('touchstart', this.handleTouchStart.bind(this));
      // this.scene.event.add('touchmove', this.handleTouchMove.bind(this));
      // this.scene.event.add('touchend', this.handleTouchEnd.bind(this));
      const planeNode = this.scene.getNodeById('image-plane');
      this.planeNode = planeNode;
      // 移除平面动画，让模型保持静止
      // this.scene.event.add('tick', this.animatePlane.bind(this));



    },
    
    animatePlane() {
      const time = Date.now() / 500;
      const scaleFactor = 2 + Math.sin(time) * 0.2; // 基于原scale 2，波动±0.2
      this.planeNode.scale.x = scaleFactor;
      this.planeNode.scale.z = scaleFactor;
 
  },
    
    
    Test: function ({ detail }) {
      const node = this.scene.getNodeById('robot');
      this.triggerEvent('touchstart', node.scale.x)
    },
    
    handleAssetsProgress: function ({ detail }) {
      const progress = detail.value;
      // console.log('assets progress', progress);
      // 可以触发进度事件给父组件显示加载进度
      this.triggerEvent('assetsProgress', { progress });
    },
    
    handleAssetsLoaded: function ({ detail }) {
      // console.log('assets loaded', detail.value);
      // this.setData({loaded: true}); // 视频相关逻辑已注释
      this.triggerEvent('assetsLoaded', detail.value);

      this.scene.event.addOnce('touchstart', this.placeNode.bind(this));
    },
    
    // handleTrackerSwitch: function ({ detail }) {
    //   const active = detail.value;
    //   const video = this.scene.assets.getAsset('video-texture', 'hikari');
    //   if (video) {
    //     active ? video.play() : video.stop();
    //   }
    // },
    
    handleARReady: function ({ detail }) {
      // console.log('arReady', this.scene.ar.arVersion);
    },
    placeNode(event) {
      const touches = event.touches;
      const { clientX, clientY } = event.touches[0];
      const { frameWidth: width, frameHeight: height } = this.scene;
      if (clientY / height > 0.8 && clientX / width < 0.2) {
        this.scene.getNodeById('setitem').visible = false;
        this.scene.ar.resetPlane();
      } else {
        //类似于固定锚点placehere
        //wx.showToast({title: '点击屏幕放置'});
        //this.scene.event.add('touchstart', () => {
        this.scene.ar.placeHere('setitem', true);
        // });
      }
      this.printWorldPosition();
    },
    
    printWorldPosition() {
      const node = this.scene.getNodeById('setitem');
      if (node && node.worldPosition) {
        // console.log('Model World Position:', node.worldPosition);
        const raw = new Float32Array(node.worldPosition._raw);
        // console.log('X:', raw[0], 'Y:', raw[1], 'Z:', raw[2]);
      } else {
        // console.warn('Node not found or world position not available.');
      }
    },
    
    // 清理旧模型资源
    clearOldModel() {
      if (!this.scene) {
        // console.warn('Scene not available for clearing');
        return;
      }
      
      try {
        // 获取旧的模型节点
        const setitemNode = this.scene.getNodeById('setitem');
        if (setitemNode) {
          // 隐藏节点
          setitemNode.visible = false;
          // console.log('隐藏旧模型节点');
        }
        
        // 尝试清除asset资源
        const assets = this.scene.assets;
        if (assets && assets.all) {
          const gltfAsset = assets.all.get('gltf-item');
          if (gltfAsset) {
            // console.log('找到旧模型asset，准备清理');
            // 注意：xr-frame的资源管理比较复杂，我们主要隐藏节点即可
            // 实际资源会在下次加载时自动替换
          }
        }
        
        // 重置状态
        this.setData({
          loaded: false
        });
        
        // 重置AR平面
        if (this.scene.ar) {
          this.scene.ar.resetPlane();
          // console.log('重置AR平面');
        }
        
        // console.log('旧模型资源清理完成');
      } catch (error) {
        console.error('清理旧模型时出错:', error);
      }
    }
  }
})